package com.zs.test;

import com.zs.pojo.Person;

import java.lang.reflect.Field;

/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/6/7 上午10:52
 */
public class AccessPersonFields {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        //通过反射加载一个Person实例
        Class<?> cls = Class.forName("com.zs.pojo.Person");
        Object person = cls.newInstance();
        //获取private String name属性
        Field name = cls.getDeclaredField("name");
        //这里name为private，这里已超出其访问的范围，不能直接访问
        //通过setAccessible方法，设定为可以访问
        name.setAccessible(true);
        //先取值
        System.out.println("赋值前的name："+name.get(person));
        //为name属性赋值
        name.set(person,"New Person");
        //展示一下赋值效果
        System.out.println("赋值后的name："+name.get(person));
    }
}
